package cn.zooz.admin.config.shiro.session;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Created by Bradish7Y on 2017/9/11.
 * 如果不考虑定时任务处理失效session，可以直接使用EnterpriseCacheSessionDAO，
 * 这个类继承CachingSessionDAO，实现了缓存，只需要把cacheManager配置为redis的
 * cacheManager就可以实现session存到redis.
 * <p>
 * CachingSessionDAO:
 * public Serializable create(Session session) {
 * Serializable sessionId = super.create(session);
 * cache(session, sessionId);
 * return sessionId;
 * }
 * <p>
 * protected void cache(Session session, Serializable sessionId) {
 * if (session == null || sessionId == null) {
 * return;
 * }
 * Cache<Serializable, Session> cache = getActiveSessionsCacheLazy();
 * if (cache == null) {
 * return;
 * }
 * cache(session, sessionId, cache);
 * }
 */
@Data
@Slf4j
public class RedisSessionDao extends AbstractSessionDAO {

    @Resource(name = "redisTemplate4Shiro")
    private RedisTemplate<Serializable, Session> redisTemplate;


    private int expireTime;// 过期时间(ms), default: 30 * 60 * 1000

    private String keyPrefix;

    @Override
    protected Serializable doCreate(Session session) {
        //todo 静态文件不创建session
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);
        log.debug("create session:{}", session.getId());
        session.setTimeout(expireTime);//ms
        redisTemplate.opsForValue().set(keyPrefix + session.getId(), session, expireTime, TimeUnit.MILLISECONDS);
        return session.getId();
    }

    //
    @Override
    protected Session doReadSession(Serializable sessionId) {
        log.debug("read session:{}", sessionId);
        if (sessionId == null) {
            return null;
        }
        return redisTemplate.opsForValue().get(keyPrefix + sessionId);
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        //todo 静态文件不更新
        log.debug("update session:{}", session.getId());
        if (session == null || session.getId() == null) {
            return;
        }

        session.setTimeout(expireTime);//ms
        //如下写法，不会更新session的超时时间，详看：SimpleSession.isTimedOut（判断sessionTimeOut是否超时）
        //redisTemplate.expire(session.getId(), expireTime, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set(keyPrefix + session.getId(), session, expireTime, TimeUnit.MILLISECONDS);
    }

    @Override
    public void delete(Session session) {
        log.debug("remote session:{}", session.getId());
        if (session == null || session.getId() == null) {
            return;
        }

        redisTemplate.delete(keyPrefix + session.getId());
    }

    @Override
    public Collection<Session> getActiveSessions() {
        Set<Session> sessions = new HashSet<>();
        Set<Serializable> sessionSet = redisTemplate.keys(keyPrefix + "*");
        if (sessionSet != null && sessionSet.size() > 0) {
            for (Serializable s : sessionSet) {
                //sessions.add((Session) s);
            }
        }
        return sessions;

        //return Collections.emptySet();
    }
}

